package com.ruoyi.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
public class WeChatUtil {

    private static final Logger log = LoggerFactory.getLogger(WeChatUtil.class);

    @Value("${wechat.appId-gzh}")
    private String appId_gzh;

    @Value("${wechat.appSecret-gzh}")
    private String appSecret_gzh;

    @Value("${wechat.templateId}")
    private String templateId;

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.appSecret}")
    private String appSecret;


    /*获取微信公众号关注用户接口地址*/
    private static final String get_userInfo_url = "https://api.weixin.qq.com/cgi-bin/user/get";

    private static final String get_user_Detail_url = "https://api.weixin.qq.com/cgi-bin/user/info";

    public String getProgramToken(){
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);
        String tokenResult = HttpUtils.sendGet(tokenUrl);
        JSONObject tokenObj = JSONObject.parseObject(tokenResult);
        String accessToken = tokenObj.getString("access_token");
        return accessToken;
    }

    public String getGzhToken(){
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId_gzh, appSecret_gzh);
        String tokenResult = HttpUtils.sendGet(tokenUrl);
        JSONObject tokenObj = JSONObject.parseObject(tokenResult);
        String accessToken = tokenObj.getString("access_token");
        return accessToken;
    }


    //传入获取的access_token获取微信关注用户列表
    public Set<String> getAllUsers(String access_token) {
        String usersGetUrl = get_userInfo_url;
        usersGetUrl += "?access_token=" + access_token;
        String result = HttpUtils.sendGet(usersGetUrl);
        log.info("获取关注列表result为："+result);
        JSONObject data = JSONObject.parseObject(result);
        Set<String> openIds = new HashSet<String>();
        Integer total = 0, count = 0;
        try {
            total = (Integer) data.get("total");
            count = (Integer) data.get("count");
            if (count > 0) {
                JSONObject openIdData = JSONObject.parseObject(data.get("data").toString());
                JSONArray openIdArray = (JSONArray) openIdData.get("openid");
                for (int i = 0; i < openIdArray.size(); i++) {
                    openIds.add((String) openIdArray.get(i));
                }
            }
            //总关注用户数超过默认一万
//            if (count < total) {
//                openIds.addAll(getUsers(openIds, usersGetUrl, access_token, (String) data.get("next_openid")));
//            } else {
                //有关注者 json才有data参数
//                if (count > 0) {
//                    JSONObject openIdData = JSONObject.parseObject(data.get("data").toString());
//                    JSONArray openIdArray = (JSONArray) openIdData.get("openid");
//                    for (int i = 0; i < openIdArray.size(); i++) {
//                        openIds.add((String) openIdArray.get(i));
//                    }
//                }
//            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return openIds;
    }

    public JSONArray getGzhUser() throws IOException {
        String access_token = getGzhToken();
        //while循环获取全部用户
        String nextOpenid = null;
        JSONArray allJsonArray = new JSONArray();
        while (true){
            String nextUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_token;
            if(null != nextOpenid){
                nextUrl += "&next_openid=" + nextOpenid;
            }
            String nextS = HttpUtils.sendGet(nextUrl);
            JSONObject jsonObject = JSONObject.parseObject(nextS);
            nextOpenid = jsonObject.getString("next_openid");
            if(jsonObject.size() > 3){
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
                for (Object gzhOpenid : jsonArray) {
                    allJsonArray.add(gzhOpenid);
                }
            }
            if(null == nextOpenid || StringUtils.isEmpty(nextOpenid)){
                break;
            }
        }
        return allJsonArray;
    }

    public JSONObject getGzhUserDetail(String openid, String access_token) {
        String url = get_user_Detail_url+"?access_token=" + access_token + "&lang=zh_CN" + "&openid=" + openid;
        String s = HttpUtils.sendGet(url);
        JSONObject jsonObject = JSONObject.parseObject(s);
        return jsonObject;
    }

    public Map<String, String> getOpenIdAndUnionIdMap(){
        HashMap<String, String> resultMap = new HashMap<>();
        String access_token = getGzhToken();
        Set<String> allUsers = getAllUsers(access_token);
        Iterator<String> iterator = allUsers.iterator();
        while (iterator.hasNext()){
            String openId = iterator.next();
            JSONObject gzhUserDetail = getGzhUserDetail(openId, access_token);
            String unionid = (String)gzhUserDetail.get("unionid");
            resultMap.put(unionid,openId);
        }
        return resultMap;
    }

}
